<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Delete } from '@element-plus/icons-vue';
import { userListService, addUserService, updateUserService, deleteUserService } from '@/api/userService.js';

const users = ref([]);
const dialogVisible = ref(false);
const userModel = ref({ id: null, username: '', password: '', type: '' });
const title = ref('');
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
};

const page = ref(1); // 当前页
const total = ref(0); // 总条数
const pageSize = ref(10); // 每页条数

const fetchUsers = async () => {
  try {
    const result = await userListService({
      username: '',
      page: page.value,
      pageSize: pageSize.value
    });

    console.log('Fetch users result:', result); // Check the structure of result

    if (result.code === 0 && result.data && Array.isArray(result.data.records)) {
      users.value = result.data.records;
      total.value = result.data.total; // Update total number of records
    } else {
      ElMessage.error('未能正确获取用户列表数据');
    }
  } catch (error) {
    console.error('Fetch users error:', error);
    ElMessage.error('获取用户列表失败');
  }
};

const addUser = async () => {
  try {
    const result = await addUserService(userModel.value);
    ElMessage.success(result.msg || '添加成功');
    await fetchUsers();
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error('添加用户失败');
  }
};

const updateUser = async () => {
  try {
    const result = await updateUserService(userModel.value);
    ElMessage.success(result.msg || '修改成功');
    await fetchUsers();
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error('修改用户失败');
  }
};

const deleteUser = (row) => {
  ElMessageBox.confirm('你确认要删除该用户吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteUserService(row.id);
      ElMessage.success('删除成功');
      await fetchUsers();
    } catch (error) {
      ElMessage.error('删除用户失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const showDialog = (row = null) => {
  dialogVisible.value = true;
  title.value = row ? '编辑用户' : '添加用户';
  if (row) {
    userModel.value = { ...row };
  } else {
    userModel.value = { id: null, username: '', password: '', type: '' };
  }
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchUsers();
};

const handlePageChange = (newPage) => {
  page.value = newPage;
  fetchUsers();
};

onMounted(() => {
  fetchUsers();
});
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>用户管理</span>
        <div class="extra">
          <el-button type="primary" @click="showDialog()">添加用户</el-button>
        </div>
      </div>
    </template>
    <el-table :data="users" style="width: 100%">
      <el-table-column label="序号" width="50" type="index"></el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="用户类型" prop="type"></el-table-column>
      <el-table-column label="创建时间" prop="createTime"></el-table-column>
      <el-table-column label="更新时间" prop="updateTime"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteUser(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form :model="userModel" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userModel.username" minlength="5" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="userModel.password" minlength="5" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label="用户类型" prop="type">
          <el-select v-model="userModel.type" placeholder="请选择">
            <el-option label="教师" value="教师"></el-option>
            <el-option label="领导" value="领导"></el-option>
            <el-option label="管理员" value="管理员"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="title === '添加用户' ? addUser() : updateUser()">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      :current-page="page"
      :page-size="pageSize"
      :total="total"
      layout="sizes, prev, pager, next, jumper"
  ></el-pagination>
</template>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
